import { login, logout, getInfo } from "@/api/admin";
import { setToken, getToken, removeToken } from "@/utils/auto";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    id: "",
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN(state, token) {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_ID: (state, id) => {
    state.id = id;
  },
};

const actions = {
  login({ commit }, personInfo) {
    const { account, password } = personInfo;
    return new Promise((resolve, reject) => {
      login({
        account: account.trim(),
        password: password,
      })
        .then((resp) => {
          const { data } = resp;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;
          if (!data) {
            reject("Verification failed, please log in again!");
          }
          const { name, id } = data;
          commit("SET_NAME", name);
          commit("SET_ID", id);

          resolve(data);
        })
        .catch((error) => {
          removeToken();
          reject(error);
        });
    });
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token)
      //   .then(() => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
      // })
      // .catch((error) => {
      //   reject(error);
      // });
    });
  },
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
